package com.ying.core.utils;

import org.springframework.beans.BeanUtils;
import org.springframework.beans.BeanWrapper;
import org.springframework.beans.BeanWrapperImpl;

import java.util.HashSet;
import java.util.Set;

/**
 * Bean工具类
 * @author 硬
 * @date 2021/12/04 20:13
 */
public class BeanUtil {

    /**
     * 拷贝Bean（忽略null值字段）
     * @author 硬
     * @date 2021/12/04 20:13
     */
    public static <S, T> void copyPropertiesIgnoreNull(S source, T target) {
        BeanUtils.copyProperties(source, target, BeanUtil.getNullPropertyNames(source));
    }

    /**
     * 获取对象中空字段数组
     */
    private static String[] getNullPropertyNames (Object source) {
        final BeanWrapper src = new BeanWrapperImpl(source);
        java.beans.PropertyDescriptor[] pds = src.getPropertyDescriptors();

        Set<String> emptyNames = new HashSet<>();
        for(java.beans.PropertyDescriptor pd : pds) {
            Object srcValue = src.getPropertyValue(pd.getName());
            if (srcValue == null) emptyNames.add(pd.getName());
        }
        String[] result = new String[emptyNames.size()];
        return emptyNames.toArray(result);
    }
}
